package com.likuicat.picture_ddd.application.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.likuicat.picture_ddd.application.service.PictureApplicationService;
import com.likuicat.picture_ddd.application.service.UserApplicationService;
import com.likuicat.picture_ddd.domain.picture.entity.Picture;
import com.likuicat.picture_ddd.domain.picture.service.PictureDomainService;
import com.likuicat.picture_ddd.domain.user.entity.User;
import com.likuicat.picture_ddd.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.likuicat.picture_ddd.infrastructure.exception.ErrorCode;
import com.likuicat.picture_ddd.infrastructure.exception.ThrowUtils;
import com.likuicat.picture_ddd.infrastructure.mapper.PictureMapper;
import com.likuicat.picture_ddd.interfaces.dto.picture.*;
import com.likuicat.picture_ddd.interfaces.vo.picture.PictureVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author fc3379757631
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-05-06 16:38:48
 */
@Service
@Slf4j
public class PictureApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureApplicationService {

    @Resource
    private PictureDomainService pictureDomainService;

    @Resource
    private UserApplicationService userApplicationService;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        return pictureDomainService.uploadPicture(inputSource, pictureUploadRequest, loginUser);
    }

    /**
     * 转化为QueryWrapper
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        return pictureDomainService.getQueryWrapper(pictureQueryRequest);
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVO pictureVO = PictureVO.objectToVO(picture);
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            if (user != null) {
                pictureVO.setUserVO(userApplicationService.getUserToUserVO(user));
            }
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> records = picturePage.getRecords();
        //创建Page<PictureVO>对象
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(records)) {
            return pictureVOPage;
        }
        //使用stream流转化
        List<PictureVO> pictureVOList = records.stream().map(PictureVO::objectToVO).collect(Collectors.toList());
        //取出userId集合
        Set<Long> collect = pictureVOList.stream().map(PictureVO::getUserId).collect(Collectors.toSet());
        //查询所有user集合,只发送一次请求，查询所有，效率更高
        Map<Long, List<User>> listMap = userApplicationService.listByIds(collect).stream().collect(Collectors.groupingBy(User::getId));
        for (PictureVO pictureVO : pictureVOList) {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (listMap.containsKey(userId)) {
                user = listMap.get(userId).get(0);
            }
            pictureVO.setUserVO(userApplicationService.getUserToUserVO(user));
        }
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null,ErrorCode.PARAMS_ERROR);
        picture.validPicture();
    }


    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        pictureDomainService.doPictureReview(pictureReviewRequest, loginUser);
    }


    /**
     * 设置审核状态：管理员自动过审并且填充审核参数；用户上传或编辑图片时，图片的状态会被重置为“待审核”。
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        pictureDomainService.fillReviewParams(picture, loginUser);
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        return pictureDomainService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
    }

    @Async //异步处理
    @Override
    public void clearPictureUrl(Picture oldPicture) {
        pictureDomainService.clearPictureUrl(oldPicture);
    }

    @Override
    public void checkPictureAuth(Picture picture, User loginUser){
        pictureDomainService.checkPictureAuth(picture, loginUser);
    }

    @Override
    public void deletePicture(long pictureId, User loginUser) {
        pictureDomainService.deletePicture(pictureId, loginUser);
    }

    @Override
    public void editPicture(Picture picture, User loginUser) {
        pictureDomainService.editPicture(picture, loginUser);
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        return pictureDomainService.searchPictureByColor(spaceId, picColor, loginUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pictureEditByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
       pictureDomainService.pictureEditByBatch(pictureEditByBatchRequest, loginUser);
    }

    @Override
    public CreateOutPaintingTaskResponse creatPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        return pictureDomainService.creatPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
    }

}




